package com.adopapa.wechatapi.xstream;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.adopapa.wechatapi.domain.event.WeChatEvent;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XstreamUtil {

	@SuppressWarnings("unchecked")
	public static <T> T XML2Bean(InputStream input, Class<T> clazz) throws IOException {
		String xml = convert2String(input);
		System.out.println(xml);
		XStream xstream = new XStream(new DomDriver());
		// xstream.alias("item", PicInfo.class);
		xstream.processAnnotations(clazz);
		return (T) xstream.fromXML(new ByteArrayInputStream(xml.getBytes()));
	}
	
	public static <T> T XML2Bean(String input, Class<T> clazz) throws IOException {
		XStream xstream = new XStream(new DomDriver());
		xstream.processAnnotations(clazz);
		return (T) xstream.fromXML(new ByteArrayInputStream(input.getBytes()));
	}
	

	public static String convert2String(InputStream inputStream) {
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		StringBuilder result = new StringBuilder();
		String line = null;
		try {
			while((line = bufferedReader.readLine()) != null) {
				result.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				inputStreamReader.close();
				inputStream.close();
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result.toString();
	}

	public static void main(String[] args) {
		Alipay alipay = null;
		try {
			InputStream inputStream = XstreamUtil.class.getResourceAsStream("alipay.xml");
			alipay = XstreamUtil.XML2Bean(inputStream, Alipay.class);
			// alipay = XstreamUtil.XML2Bean(new
			// FileInputStream("alipay.xml"), Alipay.class);
			
			inputStream = XstreamUtil.class.getResourceAsStream("heh.xml");
			WeChatEvent weChatEvent = XstreamUtil.XML2Bean(inputStream, WeChatEvent.class);
			System.err.println(weChatEvent);
			
			StringBuilder sb = new StringBuilder();
			sb.append("<alipay>");
			sb.append("<is_success>F</is_success>");
			sb.append("<error>xxxx</error>");
			sb.append("</alipay> ");
			
			inputStream = new ByteArrayInputStream(sb.toString().getBytes());
			alipay = XstreamUtil.XML2Bean(inputStream, Alipay.class);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(alipay.getIsSuccess());
		System.out.println(alipay.getRequest().getParam().get(0).getContent());
	}
}